Errors are inevitable during the process of writing programs, causing the program to fail to continue running or producing incorrect results. MATLAB provides a variety of debugging and error-handling methods. Debugging skills are largely empirical and require continuous accumulation.
Checking Errors with try-catch Statements
Section 3.3 briefly introduced the try-catch statement, which can be used to catch unknown errors.
[Example 3-26] There is a function for calculating the product of two matrices. It will throw an error when it cannot correctly calculate the result.
function matrixMultiply(A, B)
try
X = A * B
catch
disp '** Error calculating A * B.'
end
In the try-catch statement above, the statement in the try block can execute normally, and the catch block throws an error message. The following statement first defines two matrices A and B, then calls the matrixMultiply function to calculate their product. Since A and B do not satisfy the conditions for matrix multiplication (i.e., the number of columns in A does not equal the number of rows in B), an error occurs.
A = [1 2 3; 6 7 2; 0 1 5];
B = [9 5 6; 0 4 9];
matrixMultiply(A, B)
** Error calculating A * B.
Error and Warning Messages
Using MATLAB's error and warning functions can report error and warning messages and delay the program's execution.
[Example 3-27]
Such as:
if n < 1
error('n must be greater than or equal to 1.')
end
If n is less than 1, an error message "n must be greater than or equal to 1." is given.
Similarly, the warning function is used below to give a warning message.
warning('Input content must be a string')
The warning indicates that the input content must be a string.
Debugging with the "Editor" Toolbar
Using the button options in the MATLAB "Editor" toolbar, you can conveniently perform program debugging. Specific debugging methods can be broadly divided into three types: breakpoint debugging, block execution, and section-by-section debugging.
1. Breakpoint Debugging
During breakpoint debugging, the program stops running when it reaches a breakpoint, which helps quickly find the location of errors. This debugging method requires setting breakpoints first. To set a breakpoint, in the editor, left-click before the code where you want to set the breakpoint; a red dot will appear, which is the breakpoint; click again to cancel the breakpoint setting.
2. Block Execution
Select the content you want to execute in the editor, right-click the mouse, and click the "Evaluate Selection" or "Evaluate Section" command in the pop-up shortcut menu to execute the block.
3. Section-by-Section Debugging
Click the "Run and Advance" button in the "Editor" toolbar to execute the current section of the program and advance to the next section.